import TabMenu from './data';
const UiHelper = require('../common/ui-helper');
const messages = require('../common/messages');

const uiHelper = new UiHelper();

Component({
  data: {
    active: 0,
    list: TabMenu,
  },

  methods: {
    onChange(event) {
      const active = event.detail.value;
      const tab = TabMenu[active];
      const url = tab.url.startsWith('/') ? tab.url : `/${tab.url}`;
      uiHelper
        .switchTab(url)
        .then((_r) => {
          this.setData({ active });
        })
        .catch(messages.showError);
    },

    init() {
      const page = getCurrentPages().pop();
      const route = page ? page.route.split('?')[0] : '';
      const active = this.data.list.findIndex(
        (item) => (item.url.startsWith('/') ? item.url.substr(1) : item.url) === `${route}`,
      );
      this.setData({ active });
    },
  },
});
